/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * @author 品讯科技
 */

package com.px.pa.modulars.circle.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.px.basic.alone.core.base.BaseApiController;
import com.pig4cloud.pig.common.core.util.R;
import com.px.basic.alone.security.annotation.Inner;
import com.px.basic.alone.security.util.SecurityUtils;
import com.px.fastfile.service.FastfileService;
import com.px.pa.constants.ActivityStatusEnum;
import com.px.pa.constants.ActivityTypeEnum;
import com.px.pa.modulars.circle.entity.*;
import com.px.pa.modulars.circle.service.*;
import com.px.pa.modulars.circle.vo.UserVo;
import com.px.pa.modulars.job.impl.OrderTaskParam;
import com.px.pa.modulars.upms.entity.SysUser;
import com.px.pa.modulars.upms.service.SysUserService;
import com.px.pa.modulars.utils.WxQr;
import com.px.plugins.conversion.excel.util.ExcelBaseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * @author 品讯科技
 * @date 2024-08
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/circleactivity")
@Api(value = "circleactivity", tags = "管理")
public class CircleActivityController {

    private final CircleActivityService circleActivityService;
    private final CircleActivitySignService circleActivitySignService;
    private final CircleWxInfoService circleWxInfoService;
    private final FastfileService fastfileService;
    private final CircleNoticeConfigService circleNoticeConfigService;
    private final CircleActivityProgressService circleActivityProgressService;
    private final OrderJobFactory orderJobFactory;
    private final CircleUserService circleUserService;

    @Autowired
    private SysUserService sysUserService;
    private SysUser getUser(){

        System.out.println(SecurityUtils.getUser());
        SysUser user = sysUserService.getById(SecurityUtils.getUser().getId());
        return user;
    }

    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param circleActivity
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getCircleActivityPage(Page page, CircleActivity circleActivity) {
        //查询管理员所属组织

        SysUser sysUser = getUser();
        Integer userid = sysUser.getUserId();


        String tenant = sysUser.getOnlyLogo();

        Page<CircleActivity> circleActivityList = new Page<>();
        if (StringUtils.isNotEmpty(sysUser.getOrganizations())) {
            List<String> organizationsList = Arrays.asList(org.apache.commons.lang3.StringUtils.split(sysUser.getOrganizations(), ","));
            List<String> userList = new ArrayList<>();
            organizationsList.forEach(organizations -> {
                List<CircleUser> list =  circleUserService.list(new QueryWrapper<CircleUser>()
                        .eq("organizational_id",organizations));
                list.forEach(user -> {
                    userList.add(user.getId().toString());
                });
            });
            circleActivityList = circleActivityService.page(page, new QueryWrapper<CircleActivity>()
                    .like(circleActivity.getTotle() != null, "totle", circleActivity.getTotle())
                    .ge(circleActivity.getSignStartTime() != null, "sign_start_time", circleActivity.getSignStartTime())
                    .le(circleActivity.getSignEndTime() != null, "sign_end_time", circleActivity.getSignEndTime())
                    .eq("audit",1)
                    .eq("tenant_code",tenant)
                    .orderByDesc("create_time")
                  /*  .or(warrper-> warrper.or(warpper -> warpper.eq("type", ActivityTypeEnum.ACTIVITY_TYPE_ENUM_ONE.getValue())
                            .eq("uid", userid))
                    .or(userList.size() > 0, warpper -> warpper.eq("type", ActivityTypeEnum.ACTIVITY_TYPE_ENUM_TWO.getValue())
                                    .in("uid", userList)
                            )).orderByDesc("create_time")*/


            );
        } else {
            circleActivityList = circleActivityService.page(page, new QueryWrapper<CircleActivity>()
                    .like(circleActivity.getTotle() != null, "totle", circleActivity.getTotle())
                    .ge(circleActivity.getSignStartTime() != null, "sign_start_time", circleActivity.getSignStartTime())
                    .le(circleActivity.getSignEndTime() != null, "sign_end_time", circleActivity.getSignEndTime())
                    .eq("audit",1)
                    .eq("tenant_code",tenant)
                    .orderByDesc("create_time")
                   /* .or(warrpper -> warrpper.or(warpper -> warpper.eq("type", ActivityTypeEnum.ACTIVITY_TYPE_ENUM_ONE.getValue())
                            .eq("uid", userid)))
                    .orderByDesc("create_time")*/


            );
        }


        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        circleActivityList.getRecords().forEach(a -> {
            a.setActivityTimes(dateTimeFormatter.format(a.getActivityStartTime()) + "-" + dateTimeFormatter.format(a.getActivityEndTime()));
            a.setSignTimes(dateTimeFormatter.format(a.getSignStartTime()) + "-" + dateTimeFormatter.format(a.getSignEndTime()));
            //获取报名人数
            int count = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                    .eq("activity_id", a.getId())
                    .ne("is_cancel", 1));
            a.setActivitySign(count);
            if (a.getType() == 2) {
                CircleUser u=circleUserService.getById(a.getUid());
                if(u!=null){
                    a.setUserName(u.getName());
                }
            }
            if (a.getType() == 1) {

                SysUser user = sysUserService.getById(a.getUid());
                if (user != null && user.getName() != null) {
                    a.setUserName(user.getName());
                } else {
                    a.setUserName("管理员");
                }
            }

        });
        return R.ok(circleActivityList);
    }

    /**
     * 通过id查询
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        CircleActivity ca=null;

         ca=circleActivityService.getById(id);
        return R.ok(ca);
    }

    /**
     * 新增
     *
     * @param circleActivity
     * @return R
     */
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping
    public R save(@RequestBody CircleActivity circleActivity) {
        Date date1 = null;
        Date date2 = null;
        SysUser sysUser = getUser();
        String tenant = sysUser.getOnlyLogo();
        try {
            date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(circleActivity.getActivityTime()[0]);

            date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(circleActivity.getSignTime()[1]);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date1.compareTo(date2) == 1 || date1.compareTo(date2) == 0) {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            circleActivity.setActivityStartTime(LocalDateTime.parse(circleActivity.getActivityTime()[0], df));
            circleActivity.setActivityEndTime(LocalDateTime.parse(circleActivity.getActivityTime()[1].toString(), df));
            circleActivity.setSignStartTime(LocalDateTime.parse(circleActivity.getSignTime()[0].toString(), df));
            circleActivity.setSignEndTime(LocalDateTime.parse(circleActivity.getSignTime()[1].toString(), df));
            circleActivity.setCreateTime(LocalDateTime.now());
            circleActivity.setType(ActivityTypeEnum.ACTIVITY_TYPE_ENUM_ONE.getValue());

            circleActivity.setUid(SecurityUtils.getUser().getId());
            circleActivity.setTenantCode(tenant);
            circleActivityService.save(circleActivity);

            //判断活动报名开始时间是否小于当前时间
            Date dateS = Date.from(circleActivity.getSignStartTime().atZone(ZoneId.systemDefault()).toInstant());
            Date dateAS = Date.from(circleActivity.getActivityStartTime().atZone(ZoneId.systemDefault()).toInstant());
            Integer time = circleActivitySignService.getTime1(dateAS);
            //活动开始前三十分钟
            if (time <= 30) {

              //  ThreadUtil.execute(() -> {
                    circleNoticeConfigService.companyAcStart(circleActivity.getTotle(), circleActivity.getDetails(), circleActivity.getId(),circleActivity.getTenantCode());
               // });
            } else {

                try {
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localDateTime = LocalDateTime.parse(circleActivity.getSignTime()[0], df);
                    ZonedDateTime zdt = localDateTime.atZone(zoneId);
                    Date date = Date.from(zdt.toInstant());
                    //   Integer m =  circleActivitySignService.getTime1(date);
                    this.orderJobFactory.createJob(new OrderTaskParam(circleActivity.getId().toString(), Long.parseLong(circleActivity.getId().toString()), OrderTaskParam.TASK_PROJECT), (time - 30) * 60 * 1000);
                } catch (Exception e) {
                    System.out.println("活动报名开始延迟任务失败");
                }
            }


            if (dateS.compareTo(new Date()) == -1) {

               // ThreadUtil.execute(() -> {
                    circleNoticeConfigService.companyAcSignRelease(circleActivity.getTotle(), circleActivity.getDetails(), circleActivity.getId(),circleActivity.getTenantCode());
               // });
            } else {
                try {
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localDateTime = LocalDateTime.parse(circleActivity.getSignTime()[0], df);
                    ZonedDateTime zdt = localDateTime.atZone(zoneId);
                    Date date = Date.from(zdt.toInstant());
                    Integer m = circleActivitySignService.getTime1(date);
                    this.orderJobFactory.createJob(new OrderTaskParam(circleActivity.getId().toString(), Long.parseLong(circleActivity.getId().toString()), OrderTaskParam.TASK_PROJECT), m * 60 * 1000);
                } catch (Exception e) {
                    System.out.println("活动报名开始延迟任务失败");
                }
            }

            return R.ok();
        } else {
            return R.failed("活动开始时间不能早于报名截止时间");
        }

    }

    /**
     * 修改
     *
     * @param circleActivity
     * @return R
     */
    @ApiOperation(value = "修改", notes = "修改")
    @PutMapping
    public R updateById(@RequestBody CircleActivity circleActivity) {

        Date date1 = null;
        Date date2 = null;
        try {
            date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(circleActivity.getActivityTime()[0]);

            date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(circleActivity.getSignTime()[1]);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date1.compareTo(date2) == 1 || date1.compareTo(date2) == 0) {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            circleActivity.setActivityStartTime(LocalDateTime.parse(circleActivity.getActivityTime()[0], df));
            circleActivity.setActivityEndTime(LocalDateTime.parse(circleActivity.getActivityTime()[1].toString(), df));
            circleActivity.setSignStartTime(LocalDateTime.parse(circleActivity.getSignTime()[0].toString(), df));
            circleActivity.setSignEndTime(LocalDateTime.parse(circleActivity.getSignTime()[1].toString(), df));
            circleActivity.setCreateTime(LocalDateTime.now());
            return R.ok(circleActivityService.updateById(circleActivity));
        } else {
            return R.failed("活动开始时间不能早于报名截止时间");
        }

    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable Integer id) {
        circleActivitySignService.remove(new QueryWrapper<CircleActivitySign>().eq("activity_id", id));
        circleActivityProgressService.remove(new QueryWrapper<CircleActivityProgress>().eq("activity", id));
        return R.ok(circleActivityService.removeById(id));
    }

    @Scheduled(cron = "2 0 * * * ? ")
    public R corn() {
        List<CircleActivity> circleActivityList = circleActivityService.list(new QueryWrapper<CircleActivity>().eq("activity_type", 1).isNull("is_abandoned"));
        circleActivityList.forEach(a -> {
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zdt1 = a.getSignEndTime().atZone(zoneId);
            Date dateSE = Date.from(zdt1.toInstant());
            if (dateSE.compareTo(new Date()) == -1) {
                //活动报名人数
                int count = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                        .eq("activity_id", a.getId())
                        .ne("is_cancel", 1));
                if (a.getLeastPeople() > count) {
                    a.setIsAbandoned(1);  //接龙活动废弃
                    circleActivityService.updateById(a);
                }

            }

        });
        return R.ok();
    }

    /**
     * 活动总结
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "活动总结", notes = "活动总结")
    @GetMapping("/activity/conclusion")
    @Inner(value = false)
    public R getConclusion(@RequestParam("aid") Integer aid) {
        Map<String, Object> map = circleActivityService.getConclusion(aid);
        return R.ok(map);

    }


    /**
     * 活动详情二维码
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "活动详情二维码", notes = "活动详情二维码")
    @GetMapping("/activity/details/qr")
    @Inner(value = false)
    public R getDetails(@RequestParam("aid") Integer aid,HttpServletRequest request) {

        CircleWxInfo circleWxInfo = circleWxInfoService.getOne(new QueryWrapper<CircleWxInfo>()
        .eq("tenant_code",getUser().getOnlyLogo()));
        String appid = circleWxInfo.getAppid();
        String secret = circleWxInfo.getSecret();
        WxQr wxQr = new WxQr();
        MultipartFile file = wxQr.getminiqrQrTwo(aid, wxQr.getAccessToken(appid, secret).get("access_token").toString(), request);
        Map<String, Object> upResult = fastfileService.uploadFile("yctk-1256675456", file);
        return R.ok(upResult.get("kpath"));

    }

    /**
     * 个人活动开始通知
     *
     * @return
     */
    @Scheduled(cron = "30 30 * * * ? ")
    public R companyAcSignRelease() {
        Date date = new Date();
        List<CircleActivity> circleActivityList = circleActivityService.list(new QueryWrapper<CircleActivity>().eq("type", 2)
                .ge("activity_start_time", date).eq("close", 2));
        circleActivityList.forEach(a -> {
            Date date1 = Date.from(a.getActivityStartTime().atZone(ZoneId.systemDefault()).toInstant());
            long from3 = date1.getTime();
            long to3 = date.getTime();
            int minutes = (int) ((from3 - to3) / (1000 * 60));
            if (minutes <= 30) {
                circleNoticeConfigService.personalAcStart(a.getId(),a.getTenantCode());
            }
        });
        return R.ok();
    }


    /**
     * 个人活动开始通知
     *
     * @return
     */
    @Scheduled(cron = "30 0 * * * ? ")
    public R companyAcSignRelease1() {
        Date date = new Date();
        List<CircleActivity> circleActivityList = circleActivityService.list(new QueryWrapper<CircleActivity>().eq("type", 2)
                .ge("activity_start_time", date).eq("close", 2));
        circleActivityList.forEach(a -> {
            Date date1 = Date.from(a.getActivityStartTime().atZone(ZoneId.systemDefault()).toInstant());
            long from3 = date1.getTime();
            long to3 = date.getTime();
            int minutes = (int) ((from3 - to3) / (1000 * 60));
            if (minutes <= 30) {
                circleNoticeConfigService.personalAcStart(a.getId(),a.getTenantCode());
            }
        });
        return R.ok();
    }


    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/getCircleActivityPageByTouristsId")
    public R getCircleActivityPageByTouristsId(Page page, Integer id) {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        List<Integer> ids = new ArrayList<>();

        //报名成功的集合
        List<CircleActivitySign> signList = circleActivitySignService.list(new QueryWrapper<CircleActivitySign>()
                .eq("user_id", id)
                .ne("is_cancel", 1));
        signList.forEach(a -> {
            ids.add(a.getActivityId());
        });


        Page<CircleActivity> circleActivityList = circleActivityService.page(page, new QueryWrapper<CircleActivity>()
                .in("id", ids)
                .orderByDesc("create_time"));

        circleActivityList.getRecords().forEach(a -> {
            a.setActivityTimes(dateTimeFormatter.format(a.getActivityStartTime()) + "-" + dateTimeFormatter.format(a.getActivityEndTime()));
            a.setSignTimes(dateTimeFormatter.format(a.getSignStartTime()) + "-" + dateTimeFormatter.format(a.getSignEndTime()));
            //获取报名人数
            int count = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                    .eq("activity_id", a.getId())
                    .ne("is_cancel", 1));
            a.setActivitySign(count);
        });


        return R.ok(circleActivityList);
    }


    /*
        根据活动id 活动统计
     */
    @GetMapping("/statistical")
    public R statistical(
            Page page,
            Integer id) {
        Map<String, Object> map = new HashMap<>();
        //活动详情
        CircleActivity circleActivity = circleActivityService.getById(id);
        Date date = new Date();
        Date date1 = Date.from(circleActivity.getSignStartTime().atZone(ZoneId.systemDefault()).toInstant());
        Date date2 = Date.from(circleActivity.getSignEndTime().atZone(ZoneId.systemDefault()).toInstant());
        if (date.compareTo(date1) == -1) {
            circleActivity.setActivityStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_ONE.getValue());
        } else if (date.compareTo(date2) == 1) {
            circleActivity.setActivityStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_THREE.getValue());
        } else if (date.compareTo(date1) == 1 & date.compareTo(date2) == -1) {
            circleActivity.setActivityStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_TWO.getValue());
        }
        Date dateS = Date.from(circleActivity.getActivityStartTime().atZone(ZoneId.systemDefault()).toInstant());
        Date dateE = Date.from(circleActivity.getActivityEndTime().atZone(ZoneId.systemDefault()).toInstant());
        if (date.compareTo(dateS) == -1) {
            circleActivity.setActivityRunStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_ONE.getValue());
        } else if (date.compareTo(dateE) == 1) {
            circleActivity.setActivityRunStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_THREE.getValue());
        } else if (date.compareTo(dateS) == 1 & date.compareTo(dateE) == -1) {
            circleActivity.setActivityRunStatus(ActivityStatusEnum.ACTIVITY_STATUS_ENUM_TWO.getValue());
        }
        map.put("circleActivity", circleActivity);
        //活动发起人
        CircleUser circleUser = circleUserService.getById(circleActivity.getUid());
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(circleUser, userVo, true);
        map.put("userVo", userVo);
        //活动报名人数
        int activityPeopleNum = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                .eq("activity_id", circleActivity.getId())
                .ne("is_cancel", 1));
        map.put("activityPeopleNum", activityPeopleNum);
        //互动直播人数
        List<CircleActivityProgress> circleActivityProgressList1 = circleActivityProgressService.list(new QueryWrapper<CircleActivityProgress>().eq("activity", circleActivity.getId()).groupBy("uid"));
        map.put("livePeopleNum", circleActivityProgressList1.size());
        //活动访问人数
        map.put("views", circleActivity.getViews());


        List<CircleActivitySign> circleActivitySignList = circleActivitySignService.list(new QueryWrapper<CircleActivitySign>()
                .eq("activity_id", circleActivity.getId())
                .ne("is_cancel", 1));
        List<Integer> userList = new ArrayList<>();
        circleActivitySignList.forEach(a -> {
            userList.add(a.getUserId());
        });

        //活动签到人数
        int activitySignNum = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                .eq("activity_id", circleActivity.getId())
                .eq("is_signin", 1)
                .ne("is_cancel", 1));

        map.put("activitySignNum", activitySignNum);


        //参与活动男生数
        int manNum = circleUserService.count(new QueryWrapper<CircleUser>().eq("sex", 1).in("id", userList).isNotNull("sex"));
        map.put("manNum", manNum);
        //参与活动女生数
        int girlNum = circleUserService.count(new QueryWrapper<CircleUser>().eq("sex", 2).in("id", userList).isNotNull("sex"));
        map.put("girlNum", girlNum);


        Page<CircleActivitySign> circleActivitySignPage = circleActivitySignService.page(page,
                new QueryWrapper<CircleActivitySign>()
                        .eq("activity_id", circleActivity.getId())
                        .ne("is_cancel", 1));


        map.put("signPage", circleActivitySignPage);

        return R.ok(map);
    }


    @GetMapping("/exportExcel")
    @Inner(value = false)
    public void exportSign(
            HttpServletResponse response, HttpServletRequest request
    ) {
        Integer activityId = Integer.valueOf(request.getParameter("activityId"));

        /*List<CircleActivitySign> exportList = circleActivitySignService.list(new QueryWrapper<CircleActivitySign>()
                .eq("activity_id", activityId)
                .ne("is_cancel", 1)
                .orderByDesc("create_time"));*/
        List<CircleActivitySign> exportList=circleActivitySignService.exportUsers(activityId,1);
        CircleActivity activity = circleActivityService.getById(activityId);
        /*exportList.forEach(a -> {
            CircleUser user = circleUserService.getById(a.getUserId());
            a.setName(user.getName());
            a.setPhone(user.getPhone());
            a.setSex(user.getSex());
            a.setMail(user.getMail());
        });*/
        String title = activity.getTotle() + "签到表";

        ExcelBaseUtil.exportExcel(exportList, title, title, CircleActivitySign.class, title + ".xls", response);
    }


    /*
        未签到人员
     */
    @GetMapping("/noSignPeople")
    @Inner(value = false)
    public R noSignPeople(
            @RequestParam(name = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(name = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(name = "activityId", required = true) Integer activityId) {
        Page page1 = new Page(page, pageSize);

        Page<CircleActivitySign> list = circleActivitySignService.page(page1, new QueryWrapper<CircleActivitySign>()
                .eq("activity_id", activityId)
                .ne("is_cancel", 1)
                .ne("is_signin", 1)
                .orderByDesc("create_time"));
        list.getRecords().forEach(a -> {
            CircleUser user = circleUserService.getById(a.getUserId());
            a.setName(user.getName());
            a.setPhone(user.getPhone());
            a.setSex(user.getSex());
            a.setMail(user.getMail());
        });
        return R.ok(list);
    }


    /*
        人员签到状态修改
     */
    @PostMapping("/updateSignState")
    public R updateSignState(@RequestBody List<CircleActivitySign> entity) {
        entity.forEach(a -> {
            a.setIsSignin(1);
        });
        return R.ok(circleActivitySignService.updateBatchById(entity));
    }



    @GetMapping("/personalAuditPage")
    public R personalAudit(Page page, CircleActivity circleActivity){
        //查询管理员所属组织

        SysUser sysUser = getUser();


        Integer userid = sysUser.getUserId();
        String tenant = sysUser.getOnlyLogo();

        Page<CircleActivity> circleActivityList = new Page<>();
        if (StringUtils.isNotEmpty(sysUser.getOrganizations())) {
            List<String> organizationsList = Arrays.asList(org.apache.commons.lang3.StringUtils.split(sysUser.getOrganizations(), ","));
            List<String> userList = new ArrayList<>();
            organizationsList.forEach(organizations -> {
                List<CircleUser> list =  circleUserService.list(new QueryWrapper<CircleUser>()
                        .eq("organizational_id",organizations));
                list.forEach(user -> {
                    userList.add(user.getId().toString());
                });
            });
            if (userList.size()>0){
                circleActivityList = circleActivityService.page(page, new QueryWrapper<CircleActivity>()
                        .like(circleActivity.getTotle() != null, "totle", circleActivity.getTotle())
                        .ge(circleActivity.getSignStartTime() != null, "sign_start_time", circleActivity.getSignStartTime())
                        .le(circleActivity.getSignEndTime() != null, "sign_end_time", circleActivity.getSignEndTime())
                        .in("uid",userList)
                        .eq("type",ActivityTypeEnum.ACTIVITY_TYPE_ENUM_TWO.getValue())
                        .eq("audit",0)
                        .orderByDesc("create_time")
                );
            }


        }else {
            circleActivityList = circleActivityService.page(page, new QueryWrapper<CircleActivity>()
                    .like(circleActivity.getTotle() != null, "totle", circleActivity.getTotle())
                    .ge(circleActivity.getSignStartTime() != null, "sign_start_time", circleActivity.getSignStartTime())
                    .le(circleActivity.getSignEndTime() != null, "sign_end_time", circleActivity.getSignEndTime())
                    .eq("audit",0)
                    .eq("type",ActivityTypeEnum.ACTIVITY_TYPE_ENUM_TWO.getValue())
                    .eq("tenant_code",tenant)
                    .orderByDesc("create_time")


            );
        }


        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        circleActivityList.getRecords().forEach(a -> {
            a.setActivityTimes(dateTimeFormatter.format(a.getActivityStartTime()) + "-" + dateTimeFormatter.format(a.getActivityEndTime()));
            a.setSignTimes(dateTimeFormatter.format(a.getSignStartTime()) + "-" + dateTimeFormatter.format(a.getSignEndTime()));
            //获取报名人数
            int count = circleActivitySignService.count(new QueryWrapper<CircleActivitySign>()
                    .eq("activity_id", a.getId())
                    .ne("is_cancel", 1));
            a.setActivitySign(count);
            if (a.getType() == 2) {
                a.setUserName(circleUserService.getById(a.getUid()).getName());
            }
            if (a.getType() == 1) {

                SysUser user = sysUserService.getById(a.getUid());
                if (user != null && user.getName() != null) {
                    a.setUserName(user.getName());
                } else {
                    a.setUserName("管理员");
                }
            }

        });
        return R.ok(circleActivityList);
    }



    @PutMapping("/activityAudit")
    public R activityAudit(@RequestBody CircleActivity activity){
        CircleActivity updateActivity = circleActivityService.getById(activity.getId());
        updateActivity.setAudit(activity.getAudit());
        return  R.ok(circleActivityService.updateById(updateActivity));
    }

}
